package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.CloudGroupListCenter;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;

/**
 * Created by shijunting on 15-1-16.
 * 创建号码圈页面
 */
public class CreateGroupActivity extends Activity implements View.OnClickListener {

    private LinearLayout mBack;
    private LinearLayout mOk;
    private EditText mNameEdit;
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private String createGroupName;
    private ToggleButton mTbAllowAddMember, mTbCreateAttendance;
    private RelativeLayout mAddMember, mRlCreateAttendance;
    private LinearLayout mLlCreateLayout, mLlCreateSuccLayout, mLlImportLayout, mLlImportFailureMsg, mLlCreateAttendance;
    private TextView mTvTitle, mTvNewGroupDesc, mTvImportContact, mTvButtonDesc, mTvImportContactMsg, mTvImportFailureContacts, mTvImportFailureReason2;
    private static final int MSG_CREATEGROUP = 101;
    public static final int REQUIRE_AUDIT_FOR_ADD_CONTACT = 0x0020;

    private long mGroupId;
    private String mGroupName;
    private String mContactId;
    private CloudGroup mCloudGroup;
    private CloudGroupListCenter listCenter;
    private View import_failure_line1, import_failure_line2;
    private String where;
    private int type;
    private int contactCount;
    private int inAttendance;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_CREATEGROUP:
                    if (msg.arg1 == 0) {
                        try {
                            JSONObject jsonObject = (JSONObject) msg.obj;
                            JSONObject item = jsonObject.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            mGroupId = item.getLong(AsynHttpClient.KEY_GROUP_ID);
                            mGroupName = item.getString("group_name");
                            mContactId = item.getString("contact_id");
                        } catch (JSONException e) {
                            // Auto-generated catch block
                            e.printStackTrace();
                        }
                        saveCloudGroup(mGroupId);
                        if (listCenter != null) {
//                            listCenter.insertCloudGroupItem(mCloudGroup);
                            mProgressDialog.dismiss();
                            setResult(Constants.CREATE_GROUP);
//                            Toast.makeText(CreateGroupActivity.this, "创建成功!",
//                                    Toast.LENGTH_SHORT).show();
                            /*
                            AllDialogUtil dialogUtil = AllDialogUtil.getInstance(CreateGroupActivity.this);
                            dialogUtil.alertBtnStyle("已创建:" + createGroupName, false, "", "导入成员", "暂不导入");
                            dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                                @Override
                                public void onConfirmClick(Dialog lDialog) {
                                    lDialog.dismiss();
                                    Intent sendIntent = new Intent(CreateGroupActivity.this, ContactsFragment.class);
                                    sendIntent.putExtra("group_id", mAddedGroupId);
                                    sendIntent.putExtra(CloudGroup.class.getName(), mCloudGroup);
                                    CreateGroupActivity.this.setResult(520, sendIntent);
                                    finish();
                                }

                                @Override
                                public void onCancelClick(Dialog lDialog) {
                                    lDialog.dismiss();
                                    CreateGroupActivity.this.setResult(RESULT_CANCELED);
                                    CreateGroupActivity.this.finish();
                                }
                            });*/
                            getIfAttendance();
                            showSuccessLayout();
                        }
                    } else {
                        mProgressDialog.dismiss();
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(CreateGroupActivity.this, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(CreateGroupActivity.this, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                default:
                    break;
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_number_group);
        initView();
        initIntent();
    }

    private void initView() {
        mContext = this;
        mCloudGroup = new CloudGroup();
        listCenter = CloudGroupListCenter.getInstance(this);
        mBack = (LinearLayout) findViewById(R.id.ll_creategroup_btn_back);
        mOk = (LinearLayout) findViewById(R.id.ll_creategroup_btn_ok);
        mNameEdit = (EditText) findViewById(R.id.name_edit);
        mTbAllowAddMember = (ToggleButton) findViewById(R.id.tb_add_newmember);
        mTbCreateAttendance = (ToggleButton) findViewById(R.id.tb_creat_attendance);
        mAddMember = (RelativeLayout) findViewById(R.id.rl_add_member);
        mRlCreateAttendance = (RelativeLayout) findViewById(R.id.rl_creat_attendance);
        mBack.setOnClickListener(this);
        mOk.setOnClickListener(this);
        mAddMember.setOnClickListener(this);
        mRlCreateAttendance.setOnClickListener(this);
        mTbCreateAttendance.setChecked(true);
        mLlCreateAttendance = (LinearLayout) findViewById(R.id.ll_create_attendance);
        mLlCreateLayout = (LinearLayout) findViewById(R.id.ll_create_layout);
        mLlCreateSuccLayout = (LinearLayout) findViewById(R.id.ll_create_success);
        mLlImportLayout = (LinearLayout) findViewById(R.id.ll_improt_contact_msg);
        mLlImportFailureMsg = (LinearLayout) findViewById(R.id.ll_import_failure_msg);
        mTvImportContact = (TextView) findViewById(R.id.tv_import_contact);
        mTvNewGroupDesc = (TextView) findViewById(R.id.tv_newgroup_desc);
        mTvImportContact.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.creategroup_title);
        mTvButtonDesc = (TextView) findViewById(R.id.tv_btn_desc);
        mTvImportContactMsg = (TextView) findViewById(R.id.import_contact_msg);
        mTvImportFailureContacts = (TextView) findViewById(R.id.import_failure_contacts);
        mTvImportFailureReason2 = (TextView) findViewById(R.id.import_failure_reason2);
        import_failure_line1 = (View) findViewById(R.id.import_failure_line1);
        import_failure_line2 = (View) findViewById(R.id.import_failure_line2);
    }


    private void initIntent() {
        Intent intent = getIntent();
        where = intent.getStringExtra("where");
        type=intent.getIntExtra("type",0);
        if(type==1){
            mBack.setVisibility(View.GONE);
        }else{
            mBack.setVisibility(View.VISIBLE);
        }
        if ("addContact".equals(where) || "createAddContact".equals(where)) {
            mCloudGroup = (CloudGroup) intent.getSerializableExtra(CloudGroup.class.getName());
            mLlCreateLayout.setVisibility(View.GONE);
            mLlCreateSuccLayout.setVisibility(View.GONE);
            mLlImportLayout.setVisibility(View.VISIBLE);
            mBack.setVisibility(View.GONE);
            mTvTitle.setText("导入联系人");
            mTvButtonDesc.setText("完成");
            if (intent.getIntExtra("code", -1) == 0) {
                mTvImportContactMsg.setText("已成功导入" + intent.getStringExtra("success_num") + "个联系人,失败" + intent.getStringExtra("err_num") + "人");
                mTvImportFailureContacts.setText(intent.getStringExtra("err_contact_names"));
            } else {
                mTvImportContactMsg.setText(mCloudGroup.groupName + "\n号码簿导入联系人失败");
            }
            if ("0".equals(intent.getStringExtra("err_num"))) {
                mLlImportFailureMsg.setVisibility(View.INVISIBLE);
                import_failure_line1.setVisibility(View.INVISIBLE);
                import_failure_line2.setVisibility(View.INVISIBLE);
            }
            mTvImportFailureReason2.setVisibility(View.GONE);
        }
        if ("addContact".equals(intent.getStringExtra("where"))) {
            mTvImportFailureReason2.setVisibility(View.VISIBLE);
        }
        contactCount = intent.getIntExtra("contact_count", 0);
    }


    private int getGroupType() {
        int allowAdd = 0;
        if (mTbAllowAddMember.isChecked()) {
            allowAdd = 1;
        }
        return allowAdd;

    }

    private int getIfAttendance() {
        if (mTbCreateAttendance.isChecked()) {
            inAttendance = 1;
            mTvButtonDesc.setText("下一步");
        } else {
            inAttendance = 0;
            mTvButtonDesc.setText("完成");
        }
        return inAttendance;
    }

    private void setIfAttendance(int type) {
        if (type == 1) {
            mTbCreateAttendance.setChecked(true);
        } else {
            mTbCreateAttendance.setChecked(false);
        }
    }


    private void waitingDialog(String msg) {
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setTitle("请等待..");
        mProgressDialog.setMessage(msg);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    private void createGroup(String groupName, String groupType) {
        createGroupName = groupName;
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
              LocalLogin.getInstance().mSid));
        param.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_NAME, groupName));
//        param.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_DESC, groupDesc));
//        param.add(new BasicNameValuePair(AsynHttpClient.KEY_VERIFY_CODE, groupCode));
        param.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_TYPE, groupType));
//        param.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_IMG,groudImg));
        GetMsgHttpReceiver resp = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_CREATEGROUP));
        resp.mApi = AsynHttpClient.API_GROUP_ADD;
        resp.mParams = param;
        AsynHttpClient.getInstance(mContext).execCcHttp(resp);
    }

    private void saveCloudGroup(Long id) {
        mGroupId = id;
        mCloudGroup.groupId = id;
        mCloudGroup.groupName = mNameEdit.getText().toString();
//        mCloudGroup.groupDesc = null;
        mCloudGroup.groupType = getGroupType();
        mCloudGroup.contactCount = 0;
        mCloudGroup.memberCount = 0;
        mCloudGroup.updateTime = 0;

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_creategroup_btn_back:
                this.finish();
                break;
            case R.id.ll_creategroup_btn_ok:
                if (mLlCreateLayout.getVisibility() == View.VISIBLE) {
                    try {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(CreateGroupActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    } catch (Exception e) {
                    }
                    if (StringUtil.isEmpty(mNameEdit.getText().toString().trim())) {
                        Toast.makeText(mContext, "名称不能为空!", Toast.LENGTH_SHORT).show();
                    } else {
                        waitingDialog("正在创建..");
                        createGroup(mNameEdit.getText().toString(), String.valueOf(getGroupType()));
                    }
                } else if (inAttendance == 1 && "下一步".equals(mTvButtonDesc.getText())) {
                    Intent attendance = new Intent(CreateGroupActivity.this, AttendanceCreateActivity.class);
                    attendance.putExtra("group_id", mGroupId + "");
                    attendance.putExtra("group_name", mGroupName);
                    attendance.putExtra("user_type", 3);
                    attendance.putExtra("contact_id", mContactId);
                    startActivity(attendance);
                    CloudDialerActivity.mBatchOperationType = 0;
                    finish();
                } else {
                    CloudDialerActivity.mBatchOperationType = 0;
                    finish();
                }
                break;
            case R.id.rl_add_member:
                mTbAllowAddMember.toggle();
                break;
            case R.id.rl_creat_attendance:
                mTbCreateAttendance.toggle();
                getIfAttendance();
                break;
            case R.id.tv_import_contact:
                Intent sendIntent = new Intent(CreateGroupActivity.this, CloudDialerActivity.class);
                sendIntent.setAction("create_group_import_contact");
                sendIntent.putExtra("group_id", mGroupId);
                sendIntent.putExtra(CloudGroup.class.getName(), mCloudGroup);
                this.startActivityForResult(sendIntent, 0);
                break;
        }
    }

    private void showSuccessLayout() {
        mLlCreateLayout.setVisibility(View.GONE);
        mLlCreateSuccLayout.setVisibility(View.VISIBLE);
        mLlImportLayout.setVisibility(View.GONE);
        mBack.setVisibility(View.GONE);
        mTvTitle.setText("创建成功");
        mTvButtonDesc.setText("完成");
        mTvNewGroupDesc.setText(createGroupName + "\n企业创建成功");
        getIfAttendance();
    }

    private void showImportCompleteLayout() {
        mLlCreateLayout.setVisibility(View.GONE);
        mLlCreateSuccLayout.setVisibility(View.GONE);
        mLlImportLayout.setVisibility(View.VISIBLE);
        mBack.setVisibility(View.GONE);
        mTvTitle.setText("导入联系人");
        mTvButtonDesc.setText("完成");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(type==1){
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Bundle b = data.getExtras(); //data为B中回传的Intent
            String msgNote = b.getString("msgNote");//str即为回传的值

           // mLlCreateAttendance.setVisibility(View.VISIBLE);
            AllDialogUtil dialogUtil = AllDialogUtil
                  .getInstance(this);

            dialogUtil.titleMsgBtnStyle("提示", msgNote, getString(R.string.ok));
            dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                @Override
                public void onConfirmClick(Dialog lDialog) {
                    lDialog.dismiss();
                }

                @Override
                public void onCancelClick(Dialog lDialog) {
                }
            });


        }

    }
}
